import base64
import os
import sys
import urllib.parse  # 新增导入
import requests

API_KEY = "LUEeCmxq5nifS0yxzBR9m5J2"
SECRET_KEY = "2TnBiY0o0ZzGRBUzvmig6liXaGsv66xg"


def main(img):
    # 图片路径处理
    script_dir = os.path.dirname(os.path.abspath(__file__))
    image_path = os.path.join(script_dir, "..", "..", "tool", "img", f"{img}")
    image_path = os.path.abspath(image_path)

    if not os.path.exists(image_path):
        print(f"错误：找不到图片文件 {image_path}")
        print("请确保图片文件位于tool/img目录下")
        return

    # 文件大小检查
    file_size = os.path.getsize(image_path)
    print(f"图片文件大小: {file_size} 字节")
    if file_size > 4 * 1024 * 1024:
        print("警告：图片文件过大（超过4MB），可能无法被API正确处理")

    # 读取并编码图片
    with open(image_path, 'rb') as f:
        img_data = f.read()
    img_base64 = base64.b64encode(img_data).decode("utf-8")  # 简化编码写法
    print(f"Base64编码后数据长度: {len(img_base64)} 字符")

    # 获取token并检查
    access_token = get_access_token()
    if not access_token:
        return

    # 构建请求
    url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={access_token}"
    payload = {
        'image': img_base64,
        'id_card_side': 'front',
        'detect_ps': 'false',
        'detect_risk': 'false',
        'detect_quality': 'false',
        'detect_photo': 'false',
        'detect_card': 'false',
        'detect_direction': 'false',
        'detect_screenshot': 'false'
    }
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    # 正确编码payload
    payload_str = urllib.parse.urlencode(payload)

    # 发送请求
    print("正在发送请求到百度OCR API...")
    try:
        response = requests.post(url, headers=headers, data=payload_str)
        print(f"响应状态码: {response.status_code}")
        print("响应内容:")
        print(response.text)
        response.raise_for_status()  # 检查HTTP错误
        result = response.json()
        return result  # 返回OCR识别结果（JSON格式）
    except Exception as e:
        print(f"请求失败：{str(e)}")
        raise Exception(f"OCR识别失败: {str(e)}")


def get_access_token():
    """获取百度API的access_token，增加错误处理"""
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    try:
        response = requests.post(url, params=params)
        result = response.json()
        access_token = result.get("access_token")
        if not access_token:
            print(f"获取token失败：{result.get('error_description', '未知错误')}")
            return None
        return access_token
    except Exception as e:
        print(f"网络错误：{str(e)}")
        return None

# if __name__ == "__main__":
#     main()
